#!/bin/env python
# coding: utf-8
__author__ = 'donvan'
__date__ = '7/22/14'

import smtplib
import email.MIMEMultipart
import email.MIMEText
import email.MIMEBase
import os
import sys
import priviate_data


class Mail:
    def __init__(self):
        self.sender = "donvan@163.com"
        self.from_who = None
        self.receiver = ("donvan@163.com", "donvanf@hotmail.com")
        self.cc = None
        self.subject = u"this is a test email. 中文测试"
        self.attach_files = None
        self.attach_files_details = list()
        self.smtp_server = None
        self.username = None
        self.password = None
        self.content_as_html = '''
<h1> this is a test mail. </h1>
中文测试
'''
        # 构造MIMEMultipart对象做为根容器
        self.main_msg = email.MIMEMultipart.MIMEMultipart()

    def __init_server(self):
        if self.smtp_server:
            self.server = smtplib.SMTP(self.smtp_server)
            self.server.login(self.username, self.password)    # 仅smtp服务器需要验证时
        else:
            self.server = smtplib.SMTP("localhost")

    def add_file(self, file_name=None, content=None, main_type="application", sub_type="octet-stream"):
        if file_name and not content:
            assert type(self.attach_files) == tuple
            # 读入文件内容并格式化
            for file_name in self.attach_files:
                with open(file_name, 'rb') as f:
                    content = f.read()
                self.attach_files_details.append([file_name, content, main_type, sub_type])
        else:
            self.attach_files_details.append([file_name, content, main_type, sub_type])

    def __add_files(self):
        for file_details in self.attach_files_details:
            # 构造MIMEBase对象做为文件附件内容并附加到根容器
            file_name, content, main_type, sub_type = file_details
            file_msg = email.MIMEBase.MIMEBase(main_type, sub_type)
            file_msg.set_payload(content)
            email.Encoders.encode_base64(file_msg)
            ## 设置附件头
            basename = os.path.basename(file_name)
            file_msg.add_header('Content-Disposition', 'attachment', filename=basename)
            self.main_msg.attach(file_msg)

    def __make_msg(self):
        # 构造MIMEText对象做为邮件显示内容并附加到根容器
        msg_as_html = email.MIMEText.MIMEText(self.content_as_html, "html", "utf-8")
        self.main_msg.attach(msg_as_html)

        if self.attach_files:
            self.add_file(self.main_msg)

        # 设置根容器属性
        if not self.from_who:
            self.from_who = self.sender
        self.main_msg['From'] = self.from_who
        self.main_msg['To'] = ', '.join(self.receiver)
        if self.cc:
            self.main_msg['Cc'] = ','.join(self.cc)
        self.main_msg['Subject'] = self.subject
        self.main_msg['Date'] = email.Utils.formatdate()

    def send(self):
        self.__init_server()
        self.__make_msg()
        self.__add_files()
        # 用smtp发送邮件
        try:
            self.server.sendmail(self.sender, ', '.join(self.receiver), self.main_msg.as_string())
        finally:
            self.server.quit()


def test():
    mail = Mail()
    mail.sender = "donvan@163.com"
    mail.from_who = "donvanf@hotmail.com"
    mail.receiver = ("donvan@163.com", )
    mail.cc = ("donvan@163.com", )
    mail.subject = u"this is a test email. 中文测试"
    # mail.attach_files = None
    mail.smtp_server = "123.125.50.133"
    mail.username = "donvan"
    mail.password = private_data.qq_mail_passwd
    mail.content_as_html = '''
    <h1> this is a test mail. </h1>
    中文测试
    '''
    mail.send()

if __name__ == "__main__":
    test()
